<template>
  <div class="statistics_page merak-container-has-aside">
   
    <slot name="gridL"></slot>
    <div class="merak-card merak-table-wrapper">
      <div class="statistics_page_header">
        <div>
          <slot name="headerL"></slot>
        </div>
        
        <div>
          <el-button class="button_list" type="primary" @click="go_add_item">添加组件</el-button>
          <el-button class="button_list" type="primary" @click="saveTemplate">保存模板</el-button>
        </div>
       
      </div>

      <div class="grid_box" v-loading="statistics_page_loading">
        <div class="left">
          <grid-layout
            ref="gridLayoutref"
            v-model:layout="layout"
            :col-num="12"
            :row-height="30"
            :is-draggable="true"
            :is-resizable="true"
            :is-mirrored="false"
            :vertical-compact="true"
            :margin="[20, 20]"
            :use-css-transforms="true"
            @layout-ready="layoutReadyEvent"
          >
            <grid-item
              class="grid-item"
              ref="gridItem"
              v-for="(item, index) in layout"
              :x="item.x"
              :y="item.y"
              :w="item.w"
              :h="item.h"
              :i="item.i"
              :key="item.i"
              :attrid="item.i"
              :minW="item.minW"
              :minH="item.minH"
              :static="item.static"
              @resized="resizedEvent(item)"
              dragIgnoreFrom=".grid_content"
            >


            
          





              <div class="grid_every_box">
                <div :class="'grid_header ' + item.class">
                  <div class="grid_header_l">
                    {{ item.tit }}
                  </div>
                  <div class="grid_header_r">
                    <!-- 点点点 -->
                    <el-dropdown>
                      <span class="el-dropdown-link btn">
                        <el-icon><MoreFilled /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item>导出Excel</el-dropdown-item>
                          <el-dropdown-item>列表模式</el-dropdown-item>
                          <el-dropdown-item>移除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>

                <div class="grid_content">

                  <!-- 传入过来的插槽 -->
                  <slot :name="'slot_'+item.i" :item='item'> </slot>
                </div>
                      




 

              </div>





            </grid-item>
          </grid-layout>
          <!-- <div ref="echartsRef" style="height: 400px; width: 500px">gamePlay</div> -->
          <!-- <canvas ref="echartsRef1" style="height: 400px; width: 500px">gamePlay</canvas> -->
        </div>
      </div>
    </div>

    <!-- 新增抽屉start -->

    <el-dialog
      modal-class="merak_modal"
      v-model="addtemolates_modal"
      direction="rtl"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="700"
    >
      <template #header>
        <div class="merak_modal_title">添加工作台组件</div>
      </template>
      <div>
        <el-row :gutter="40">
          <el-col :span="12" v-for="template_every in templates_arr">
            <div class="template_every">
              <div class="template_every_l">
                <div class="tit">
                  {{ template_every.tit }}
                </div>
                <div class="desc">
                  {{ template_every.desc }}
                </div>
              </div>
              <div class="template_every_r">
                <span>
                  <el-button
                    @click="add_item_page(template_every)"
                    :disabled="template_every.is_inpage"
                    size="small"
                    type="default"
                  >
                    {{ template_every.is_inpage ? "已存在" : "添加组件" }}
                  </el-button>
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 新增抽屉end -->
  </div>
</template>
<script setup>
import { onBeforeMount, watch,ref, reactive, onMounted, getCurrentInstance, nextTick  } from "vue";
import { useRouter } from "vue-router";
import ECharts from "@/components/ECharts/index.vue";
import { saveStatistics, getStatistics,getEveryStatistics } from "@/api/modules/personalManagementApi/holiday";
import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

const router = useRouter();
const goPage = () => {
  router.push("/caseThree/index");
};

const open=ref(false)
const value3=ref([])

const search_mouseenter = event => {
  console.log(event)
  open.value=true;



}
const search_mouseover = event => {
  console.log('离开')
  console.log(event)
  console.log(event.relatedTarget.className  )
  if(!event.relatedTarget.className.includes('el-')){
    open.value=false;
  }



}
const echartsRefMap = ref({});
const handleSetFromMap = (el, item) => {
  if (el) {
    echartsRefMap.value[`echarts_Ref_${item.name_ref}`] = el;
  }
};


// 更新图表
const resizeEcarts = (ecarts_refs) => {
  if (ecarts_refs) {
    ecarts_refs.forEach(chart=>{
              if(echartsRefMap.value[`echarts_Ref_${chart}`]){
                echartsRefMap.value[`echarts_Ref_${chart}`].resize();
              }
    })
  }
};
// 获取图表，帮忙发送ajax
const updataEcarts = (every,params) => {
  console.log(every)
  console.log("发送接口")
  if(every.geturl){
    getEveryStatistics(every.geturl,params).then(res => {
    if (res.code == ResultEnum.SUCCESS) {
        console.log(res.data)

        every.contentData.echartData=res.data;
      
        resizeEcarts(every.echartsRef)
    }
  });
  } 
};





const handleScroll = (event,type) => {
  var that=this;
    // 处理滚动事件
  var elements = document.getElementsByClassName("vue-grid-item");
  var grid_box= document.querySelector(".grid_box");
  var targettop=0;
  if(!(type=='init')){
    targettop=event.target.scrollTop; 
  }
  var grid_box_h = grid_box.offsetHeight;
  grid_box_h=grid_box_h+50;

  for (let index = 0; index < elements.length; index++) {
    const cur = elements[index];
    var style = cur.style;
    var transform = style.transform || '';
    var transformY = transform.match(/translate3d\(\d+px,\s*(\d+)px,\s*(\d+)px\)/i)[1];
    if(transformY -  targettop<= grid_box_h){

      layout.value.forEach((item,index)=>{
      
      if(item.i== cur.getAttribute("attrid")){
       
        if(!item.status){
          console.log("渲染图标"+item.i)
          setTimeout(() => {
          
           console.log(item)
           
          if(item.is_need_show){
            console.log()
            if(!item.status){
              item.status=true;
              updataEcarts(item,{})
            }
            
            

            

          //   item.contentData.echartData={
          //         title: {
          //           text:'',
          //           textStyle: {
          //             fontSize: 14
          //           }
          //         },
          //         tooltip: {},
          //         legend: {
          //           data: ["订单额123123123123123123123"]
          //         },
          //         xAxis: {
          //           data: ["衬衫", "羊毛衫", "雪纺衫"]
          //         },
          //         yAxis: {},
          //         series: [
          //           {
          //             name: "销量",
          //             type: "bar",
          //             data: [5, 20, 36]
          //           }
          //         ]
          //  }

         
            
          
         
         
          }else{

            item.contentData={
              aa:'aaa',
              bb:'bbb'
            }
            item.status=true;

            emits("changeEchart",item)
          }
            
          

          



              
           
           
          

         }, 2000);
        }





    	}




     })



  }

}





};

const statistics_page_loading = ref(true);
onMounted(() => {
  nextTick(() => {
     var elmain = document.querySelector(".grid_box");
     elmain.addEventListener("scroll", handleScroll);

      getStatisticsFun();
   });
  
});

const getStatisticsFun = () => {
  // var onecharts = layout.value[0].charts;
  // var twocharts = layout.value[1].charts;
  // var eightcharts = layout.value[8].charts;

  getStatistics({ route: "TEST" }).then(res => {
    statistics_page_loading.value = false;
       if (res.code == ResultEnum.SUCCESS) {
           console.log(res.data)
    //  layout.value=res.data;

    //  layout.value[0].charts=onecharts;
    //  layout.value[0].status=true;

    //  layout.value[1].charts=twocharts;
    //  layout.value[1].status=true;

    //  layout.value[2].charts=onecharts;
    //  layout.value[2].status=true;

    //  layout.value[8].charts=eightcharts;
    //  layout.value[8].status=true;
    //  console.log( layout.value[0])

    //  layout.value.forEach((item,index)=>{
    // 	if(item.i==1 || item.i==0 || item.i==8 || item.i==2){

    // 	}else{
    // 		console.log(item.w)
    // 		if(item.w>2){
    // 			item.charts=twocharts;
    // 			item.status=true;
    // 		}else{
    // 			item.charts={};
    // 			item.status=false;
    // 		}

    // 	}
    //  })

      }
  });
};
const saveTemplate = () => {
  console.log(layout.value);
  var postlayout = JSON.parse(JSON.stringify(layout.value));
  postlayout.forEach(item => {
    item.charts = {};
    item.status = false;
  });

  saveStatistics({ route: "TEST", config: layout.value }).then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      successMsg("保存成功");
    }
  });
};

const addtemolates_modal = ref(false);
const go_add_item = () => {
  addtemolates_modal.value = true;
};

const gridLayoutref = ref();
const add_item_page = alert_item => {
  console.log(alert_item);
  console.log(layout.value);

  let maxValueY = null;
  layout.value.forEach((item, index) => {
    console.log(item.y);
    var cury = item.y;
    if (maxValueY === null || cury > maxValueY) {
      maxValueY = cury;
    }
  });

  console.log(maxValueY);

  var maxValueX = 0;
  var last_w = layout.value[layout.value.length - 1].w;
  console.log(last_w);
  if (12 - last_w > 5) {
    maxValueX = 12 - last_w;
  }

  var new_obj = {
    charts: {
      title: {
        text: alert_item.tit,
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {},
      legend: {
        data: ["订单额"]
      },
      xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫"]
      },
      yAxis: {},
      series: [
        {
          name: "销量",
          type: "bar",
          data: [5, 20, 36]
        }
      ]
    },
    x: 0,
    y: maxValueY,
    w: 6,
    h: 8,
    i: alert_item.id,
    class: "has_blue_line",
    name: alert_item.tit,
    minW: "",
    minH: "",
    maxW: "",
    maxH: "",
    status: true
  };
  console.log(new_obj);
  layout.value.push(new_obj);
  layoutUpdateFun();
  addtemolates_modal.value = false;
  alert_item.is_inpage = true;
};

// 切换下拉框,更新图表
const change_echarts_data = item => {
  item.charts = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      orient: "vertical",
      left: 10,
      data: ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
    },
    series: [
      {
        name: "访问来源",
        type: "pie",
        radius: ["50%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "30",
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 335, name: "直接访问" },
          { value: 310, name: "邮件营销" },
          { value: 234, name: "联盟广告" },
          { value: 135, name: "视频广告" },
          { value: 1548, name: "搜索引擎" }
        ]
      }
    ]
  };
};

const layoutUpdateFun = () => {
  gridLayoutref.value.layoutUpdate();
  gridLayoutref.value.updateHeight();
};



const templates_arr = ref([
  {
    tit: "在售商品货号",
    desc: "提供个人范围内任务、代码相关的统计数据",
    is_inpage: true,
    id: "11"
  },
  {
    tit: "在售折扣商品货号",
    desc: "在售品类、代码相关的统计数据",
    is_inpage: false,
    id: "12"
  },
  {
    tit: "企发销售属性",
    desc: "在售品类、代码相关的统计数据",
    is_inpage: false,
    id: "13"
  },
  {
    tit: "电子标签申请",
    desc: "在售品类、代码相关的统计数据",
    is_inpage: false,
    id: "14"
  },
  {
    tit: "在售折扣商品货号",
    desc: "在售品类、代码相关的统计数据",
    is_inpage: false,
    id: "15"
  }
]);

const value = ref("Option1");
const value1 = ref("Option2");
const options = [
  {
    value: "Option1",
    label: "全站"
  },
  {
    value: "Option2",
    label: "俄境内标准订单"
  },
  {
    value: "Option3",
    label: "跨境直供"
  },
  {
    value: "Option4",
    label: "跨境拼单"
  },
  {
    value: "Option5",
    label: "Option5"
  }
];


const goods_type=ref();
const goods_spliuer=ref();
const options_goods_type=[
  {
    value: "Option1",
    label: "鞋"
  },
  {
    value: "Option2",
    label: "包"
  },
  {
    value: "Option3",
    label: "服装"
  }
];
const options_goods_spliuer=[
  {
    value: "Option1",
    label: "DELORAS"
  },
  {
    value: "Option2",
    label: "Бледно-розовый"
  },
  {
    value: "Option3",
    label: "bledno-rozoviy_642"
  }
];


// 初始化模块完成
const layoutReadyEvent=(newLayout)=>{
      console.log("Ready layout: ", newLayout)
      nextTick(() => {
      handleScroll(event,'init')
    })

      
}








// static: true,
const delItem = layout_item => {
  delConfimMsg({
    callback: val => {
      if (val == "confirm") {
        layout.value.forEach((item, index) => {
          console.log(item, index);
          if (item.i == layout_item.i) {
            console.log("删除");
            layout.value.splice(index, 1);
          }
        });

        templates_arr.value.forEach((item, index) => {
          if (item.id == layout_item.i) {
            item.is_inpage = false;
          }
        });
        console.log(templates_arr.value);

        layoutUpdateFun();
      }
    }
  });
};


const formLabelAlign = reactive({
  name: '',
  region: '',
  type: '',
})



const resizedEvent = (item) => {
  // const msg = "RESIZED i=" + i + ", X=" + newX + ", Y=" + newY + ", H(px)=" + newHPx + ", W(px)=" + newWPx;
   resizeEcarts(item.echartsRef)
};





const layout=ref([]);
const expressList = ref([])
const props = defineProps({
  layoutData: [String, Number],
  refs:[String, Number],
  isId: {
      default: false,
      type: Boolean
  }, //是否需要id传默认false
  isAll: {
      default: false,
      type: Boolean
  },//是否开启查找全部功能，默认false

})
const emits = defineEmits(['update:listValue','changeEchart']);



const getExpress = () => {
  console.log(props.layoutData)
  console.log(props.refs)
  echartsRefMap.value=props.refs;
  console.log(  echartsRefMap.value)
  layout.value=props.layoutData;

  

  
}
onBeforeMount(() => {
  console.log("Sdfsdafsd")
  getExpress()
})



</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
